package com.xmb.wechat.view.alipay;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.nil.sdk.utils.DateUtils;
import com.xmb.wechat.R;
import com.xmb.wechat.R2;
import com.xmb.wechat.base.BaseActivity;
import com.xmb.wechat.bean.WechatContactBean;
import com.xmb.wechat.definterface.CommonIAndSListener;
import com.xmb.wechat.definterface.HintListener;
import com.xmb.wechat.entity.AliPayGatheringEntity;
import com.xmb.wechat.helper.DataHelper;
import com.xmb.wechat.util.MoneyFormat;

import java.util.Date;
import java.util.Random;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @Author lijiangop
 * @CreateTime 2020/5/21 09:27
 */
public class AliPayGatheringActivity extends BaseActivity {

    @BindView(R2.id.tv_received)
    TextView     mTvReceived;
    @BindView(R2.id.tv_transfer)
    TextView     mTvTransfer;
    @BindView(R2.id.iv_receiver)
    ImageView    mIvReceiver;
    @BindView(R2.id.tv_receiver)
    TextView     mTvReceiver;
    @BindView(R2.id.et_account)
    EditText     mEtAccount;
    @BindView(R2.id.et_money)
    EditText     mEtMoney;
    @BindView(R2.id.tv_state)
    TextView     mTvState;
    @BindView(R2.id.et_way)
    EditText     mEtWay;
    @BindView(R2.id.ll_way)
    LinearLayout mLlWay;
    @BindView(R2.id.et_reason)
    EditText     mEtReason;
    @BindView(R2.id.et_type)
    EditText     mEtType;
    @BindView(R2.id.et_order_num)
    EditText     mEtOrderNum;
    @BindView(R2.id.tv_time)
    TextView     mTvTime;
    @BindView(R2.id.tv_way_tag)
    TextView     mTvWagTag;
    @BindView(R2.id.et_tag_and_remark)
    EditText     mEtTagAndRemark;
    @BindView(R2.id.et_real_name)
    EditText     mEtRealName;
    @BindView(R2.id.ll_real_name)
    LinearLayout mLlRealName;

    private AliPayGatheringEntity mEntity;

    public AliPayGatheringActivity() {
        super(R.layout.activity_alipay_gathering);
    }

    @Override
    protected void initView() {
        mEntity = new AliPayGatheringEntity();
        setState(true);
        showTime(new Date());
        showExemption(new HintListener() {
            @Override
            public void onConfirm() {
                //do nothing
            }

            @Override
            public void onCancel() {
                AliPayGatheringActivity.this.finish();
            }
        });
    }

    @OnClick({R2.id.tv_received, R2.id.tv_transfer, R2.id.re_receiver, R2.id.ll_state, R2.id.ll_time, R2.id.btn_preview})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.tv_received) {
            setState(true);
        } else if (id == R.id.tv_transfer) {
            setState(false);
        } else if (id == R.id.re_receiver) {
            KeyboardUtils.hideSoftInput(this);
            showRoleChooseSender(this, false, 1, false, null);
        } else if (id == R.id.ll_state) {
            showListDialog(DataHelper.getGatheringStateType(), new CommonIAndSListener() {
                @Override
                public void onChoose(int i, String s) {
                    if (i == 0) {
                        mTvState.setTextColor(Color.parseColor("#f9840d"));
                        mLlWay.setVisibility(View.GONE);
                    } else {
                        mTvState.setTextColor(getResources().getColor(R.color.black_60));
                        mLlWay.setVisibility(View.VISIBLE);
                    }
                    mTvState.setText(s);
                    mEntity.setState(i);
                    mEntity.setTradeState(s);
                }
            });
        } else if (id == R.id.ll_time) {
            KeyboardUtils.hideSoftInput(this);
            @SuppressLint("SimpleDateFormat")
            TimePickerView pvTime = new TimePickerBuilder(this, (date, v) -> {//选中事件回调
                showTime(date);
            }).setType(new boolean[]{false, true, true, true, true, false})// 默认全部显示
                    .setCancelText("取消")//取消按钮文字
                    .setSubmitText("确定")//确认按钮文字
                    .setTitleSize(20)//标题文字大小
                    .setTitleText("时间")//标题文字
                    .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                    .isCyclic(true)//是否循环滚动
                    .setSubmitColor(getResources().getColor(R.color.wechat_tab_bg_green))//确定按钮文字颜色
                    .setCancelColor(getResources().getColor(R.color.wechat_tab_bg_green))//取消按钮文字颜色
                    .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                    .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                    .build();
            pvTime.show();
        } else if (id == R.id.btn_preview) {
            doPreview();
        }
    }

    private void setState(boolean isReceived) {
        mTvReceived.setSelected(isReceived);
        mTvTransfer.setSelected(!isReceived);
        mEntity.setReceived(isReceived);
        mTvWagTag.setText(isReceived ? "收款方式" : "付款方式");
        mLlRealName.setVisibility(isReceived ? View.GONE : View.VISIBLE);
    }


    private void doPreview() {
        //付款对象
        String nickName = mTvReceiver.getText().toString().trim();
        if (mEntity.getPayerId() == -1) {
            ToastUtils.showShort("请选择付款对象");
            return;
        }
        //真实姓名
        String realName = mEtRealName.getText().toString().trim();
        if (!mEntity.isReceived() && TextUtils.isEmpty(realName)) {
            ToastUtils.showShort("请填写真实姓名");
            return;
        }
        realName = mEntity.isReceived() ? nickName : nickName + "(" + realName + ")";
        //付款账号
        String account = mEtAccount.getText().toString().trim();
        if (TextUtils.isEmpty(account)) {
            ToastUtils.showShort("请填写付款账号");
            return;
        }
        mEntity.setPayerAccount(mEntity.isReceived() ? nickName + " " + account : realName + " " + account);
        //金额
        String money = mEtMoney.getText().toString().trim();
        if (TextUtils.isEmpty(money)) {
            ToastUtils.showShort("请填写收款金额");
            return;
        }
        mEntity.setMoney(parseMoney(money));
        //交易状态
        String state = mTvState.getText().toString().trim();
        if (TextUtils.isEmpty(state) || TextUtils.equals(state, "请选择")) {
            ToastUtils.showShort("请选择交易状态");
            return;
        }
        mEntity.setTradeState(state);
        //收款方式
        String way = mEtWay.getText().toString().trim();
        way = TextUtils.isEmpty(way) ? "余额" : way;
        mEntity.setGatheringWay(way);
        //收款理由
        String reason = mEtReason.getText().toString().trim();
        reason = TextUtils.isEmpty(reason) ? "个人收款" : reason;
        mEntity.setReason(reason);
        //账单分类
        String type = mEtType.getText().toString().trim();
        type = TextUtils.isEmpty(type) ? "转账充值" : type;
        mEntity.setBillType(type);
        //标签和备注
        String tagAndRemark = mEtTagAndRemark.getText().toString().trim();
        tagAndRemark = TextUtils.isEmpty(tagAndRemark) ? "添加" : tagAndRemark;
        mEntity.setTagAndRemark(tagAndRemark);
        //订单号
        String orderNum = mEtOrderNum.getText().toString().trim();
        orderNum = TextUtils.isEmpty(orderNum) ? getRandomOrderNum() : orderNum;
        mEntity.setOrderNum(orderNum);

        AliPayGatheringDetailActivity.start(this, mEntity,realName);
    }

    private String parseMoney(String money) {
        try {
            return MoneyFormat.formatMoney(money);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    private String getRandomOrderNum() {
        return DateUtils.getCurDateByFormat("yyyyMMdd") + "200040011100" +
                new Random().nextInt(10) +
                new Random().nextInt(10) +
                new Random().nextInt(10) +
                new Random().nextInt(10) +
                new Random().nextInt(10) +
                new Random().nextInt(10) +
                new Random().nextInt(10) +
                new Random().nextInt(10) +
                new Random().nextInt(10) +
                new Random().nextInt(10) +
                new Random().nextInt(10) +
                new Random().nextInt(10);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE_OTHER_SEND || requestCode == REQUEST_CODE_CHOOSE_NEW_ADD_SEND) {
            if (data == null)
                return;
            WechatContactBean result = (WechatContactBean) data.getSerializableExtra("result");
            if (result == null)
                return;
            showPayer(result);
        }
    }

    private void showPayer(WechatContactBean result) {
        WechatContactBean.setupAvatarIntoImageView(result, mIvReceiver, 12);
        mTvReceiver.setText(TextUtils.isEmpty(result.getName()) ? "" : result.getName());
        mEtAccount.setText(getRandomPhoneNum(result.getName()));
        //数据
        mEntity.setPayerId(result.getId());
    }

    private String getRandomPhoneNum(String name) {
        if (TextUtils.isEmpty(name))
            return "";
        String phone = "135******";
        String hashCode = String.valueOf(Math.abs(name.hashCode()));
        if (hashCode.length() > 1) {
            phone += hashCode.substring(0, 2);
        } else
            phone += "18";
        return phone;
    }

    private void showTime(Date date) {
        mTvTime.setText(DateUtils.getStringByFormat(date, "yyyy-MM-dd HH:mm"));
        mEntity.setTime(mTvTime.getText().toString());
    }
}
